import aiohttp
from common import get_redis, single_instance

@single_instance
class WechatClient():
    def __init__(self, appid, appsecret, apptoken):
        self.appid = appid
        self.appsecret = appsecret
        self.apptoken = apptoken

    async def get_token(self):
        # try to get token from redis
        redis = await get_redis()
        token = await redis.get("smarthome:wechat:token")
        if token:
            print("Redis token")
            return token
        uri = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}"
        async with aiohttp.request('GET', uri.format(self.appid, self.appsecret)) as r:
            data = await r.json()
        token = data['access_token']
        print("refresh token")
        await redis.setex(
            key="smarthome:wechat:token", 
            seconds=data['expires_in'],
            value=token)
        return token

    async def send_template(self, to_user_name, template_id, msg_data, url="", miniprogram=None):
        template_data = {
            "touser": to_user_name,
            "template_id": template_id,
            "url": url,
            "data": msg_data
        }
        if miniprogram:
            template_data['miniprogram'] = miniprogram
        token = await self.get_token()
        uri = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={}"
        async with aiohttp.request('POST', uri.format(token), json=template_data) as resp:
            echo = await resp.json()
        return echo
        

